import { Component, DoCheck } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import * as $ from 'jquery';
import * as echarts from 'echarts';
import { ListPage } from '../list/list';

import { DetailsService } from "./services/details.service";

import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

import * as moment from 'moment'

import { Message } from '@stomp/stompjs';
import { StompService, StompState } from '@stomp/ng2-stompjs';

import { Utils } from './Utils';





@IonicPage()
@Component({
  selector: 'page-details',
  templateUrl: 'details.html',
})
export class DetailsPage implements DoCheck {


  va = false;
  icons: string = "camera";
  icons1: string = "1";
  oldicons1: string = "1";
  // start: any = {};
  // end: any = {};
  start = Utils.dateFormat(new Date(), 'yyyy-MM-ddTHH:mm:ss+08:00');
  end = Utils.dateFormat(new Date(), 'yyyy-MM-ddTHH:mm:ss+08:00');
  data;
  echart;
  echart1;
  chartX;
  chartY;
  chart1X;
  chart1Y;
  chart;
  chart1;
  starte = 60;
  text;

  message$: Observable<Message>;
  state$: Observable<any>;
  subscription$: Subscription;
  subscribed: boolean;
  dataQuota;

  dataRes;
  dataName;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public service: DetailsService,
    public directives: StompService) {
    this.data = this.navParams.get('data')
    console.log(666,this.data)
    if (this.data.typeTag == "tension-em") {
      this.dataQuota = 0;
    } else {
      this.dataQuota = 1;
    }
  }
  avg;
  max;
  min;
  count;
  length;
  ionViewDidLoad() {
    this.subscribed = false;
    this.real();
    //获取单位
    this.service.getname(this.data.type)
    .subscribe(res => {
      this.dataName = res;
      this.dataRes = res;
      console.log(777,this.dataName);
      console.log(this.dataName[0].name);
      // this.unit1 = res[0].unit;
      // this.unit2 = res[1].unit;
    })


  }
  // getdata(typeId, deviceId, dataQuota, start, end) {
  //   this.service.getStatistics(typeId, deviceId, dataQuota, start, end)
  //     .subscribe(res => {
  //       console.log(res);
  //       this.count = res['count']
  //       this.avg = res['avg'].toFixed(3);
  //       this.max = res['max'].toFixed(3);
  //       this.min = res['min'].toFixed(3);
  //     })
  // }

  //图标数据(动态)
  getecharts(x, y, bottom) {
    let series = [];
    let color = ["#eda509", "#00eaff"]
    y.map((item, i) => {
      const s = {
        name: this.dataName[i].name,
        itemStyle: {
          normal: {
            lineStyle: {
              color: color[i]
            }
          }
        },
        data: item.map(function (i) {
          return i;
        }),
        type: 'line'
      }
      series.push(s)
    })
    let option = {
      color:["#eda509", "#00eaff"],
      legend: {
        data: this.dataName.map(item=>{
          return item.name
        })
      },
      backgroundColor: '#e2e9f5',//背景色
      title: {
        text: ''
      },
      tooltip: {
        trigger: 'axis'
      },

      dataZoom: {
        orient: 'horizontal',      // 布局方式，默认为水平布局，可选为：'horizontal' ¦ 'vertical'
        backgroundColor: 'rgba(0,0,0,0)',       // 背景颜色
        dataBackgroundColor: '#eee',            // 数据背景颜色
        fillerColor: 'rgba(144,197,237,0.2)',   // 填充颜色
        handleColor: 'rgba(70,130,180,0.8)',   // 手柄颜色
        start: 80,                                // 数据窗口范围的起始百分比,表示30%
        end: 100,                                  // 数据窗口范围的结束百分比,表示70%
        startValue: 50,                           // 数据窗口范围的起始数值
        endValue: 100                           // 数据窗口范围的结束数值
      },

      grid: {
        left: '3%',
        right: '4%',
        bottom: bottom,
        top: '5%',
        containLabel: true
      },

      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: x
      },
      yAxis: {
        type: 'value'
      },
      series: series
    }
    return option;
  }
  getHistory() {
    this.service.getCountHistory(this.data.typeTag, this.data.id, 15)
      .subscribe(res => {
        this.chart1X = [];
        this.chart1Y = [];
        this.chartX = this.chart1X;
        this.chartY = this.chart1Y;
        if (res.length == 0) {
          return;
        }
        let y1 = [], y2 = [];
        let data = res[0].data.length;
        res.map((item, i) => {
          //记录有几条曲线
          this.chart1X.push(moment(item.time, "YYYYMMDDHHmmssSSS").format("YY/MM/DD HH:mm:ss"));
          y1.push(item.data[0].toFixed(3))
          if (data == 2) {
            y2.push(item.data[1].toFixed(3))
          }
        })
        this.chart1Y.push(y1)
        if (y2.length !== 0) {
          this.chart1Y.push(y2)
        }
        this.chartX = this.chart1X;
        this.chartY = this.chart1Y;
        this.chart = this.getecharts(this.chartX, this.chartY, '10%');
        this.chart1 = this.getecharts(this.chart1X, this.chart1Y, '15%');
        this.starte = 98;
        this.echart.setOption(this.chart);
      })
  }

  //每次进出都会调用
  ionViewWillEnter() {
    this.getHistory()
    if (this.icons == "bookmark") {
      $('.start').show()
      $('.end').show();
      $('.time').show();
      $('#chart').hide();
      $('#chart1').show();
      $(".search").show()
    } else {
      $('.start').hide();
      $('.end').hide();
      $('.time').hide();
      $('#chart1').hide();
      $(".search").hide()
    }

    const now = new Date();
    const nowStamp = now.getTime();
    const aDay = 3600 * 24 * 1000;
    const startday = nowStamp - aDay;
    const startTime = new Date(startday).toLocaleString();
    const endTime = now.toLocaleString();
    const sind = startTime.indexOf('午'), eind = endTime.indexOf("午");;

    const start = moment(startTime.slice(0, sind - 1) + startTime.slice(sind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
    const end = moment(endTime.slice(0, eind - 1) + endTime.slice(eind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
    // this.getdata(this.data.typeTag, this.data.id, this.dataQuota, start, end)
    const ec = echarts as any;
    const container = document.getElementById('chart');
    this.echart = ec.init(container);

  }
  ionViewWillLeave() {
    this.unsubscribe()
  }

  //点击获取测点数据总数
  countData(start, end) {
    this.service.count(this.data.typeTag, this.data.id, start, end)
      .subscribe(res => {
        console.log(11111, res);
        this.length = res;
        var length = this.length;
        this.gettimehistory(start, end, length);
      })

  }

  search() {
    const start = typeof this.start, end = typeof this.end;
    if (start == 'object' && end == 'object') {
      this.text = "请选择开始时间与结束时间"
    } else if (start == 'object') {
      this.text = "请选择开始时间"
    } else if (end == "object") {
      this.text = "请选择结束时间"
    } else if (start == 'string' && end == 'string') {
      const start = moment(this.start, "YYYY-MM-DD't'HH:mm:ss'Z'").format('YYYYMMDDHHmmssSSS');
      const end = moment(this.end, "YYYY-MM-DD't'HH:mm:ss'Z'").format('YYYYMMDDHHmmssSSS');
      console.log(222, start);
      console.log(222, end);
      if (start < end) {

        $('.timeA').removeClass('segment-activated');

        this.countData(start, end);
        // this.gettimehistory(start, end)
        this.text = undefined;
        setTimeout(() => {
          $(".ant-pagination-jump-next").children("a").text("···")
        }, 100)
      } else {
        this.text = "请输入正确的时间";
      }
    }
  }
  click() {
    this.text = undefined;
  }

//获取测点数量




  gettimehistory(start, end, length) {
    this.service.getTimeHistory(this.data.typeTag, this.data.id, start, end, length)
      .subscribe(res => {
        this.chart1X = [];
        this.chart1Y = [];
        if (res.length == 0) {
          $(".time").hide()
          return;

        }
        let y1 = [], y2 = [];
        let data = res[0].data.length;
        res.map((item, i) => {
          //记录有几条曲线
          this.chart1X.push(moment(item.time, "YYYYMMDDHHmmssSSS").format("YY/MM/DD HH:mm:ss"));
          y1.push(item.data[0].toFixed(3))
          if (data == 2) {
            y2.push(item.data[1].toFixed(3))
          }
        })
        this.chart1Y.push(y1)
        if (y2.length !== 0) {
          this.chart1Y.push(y2)
        }
        this.chart1 = this.getecharts(this.chart1X, this.chart1Y, '15%');
        this.echart1.setOption(this.chart1);
      })
  }
  ngDoCheck() {
    if (this.icons1 !== this.oldicons1) {
      this.oldicons1 = this.icons1
      switch (this.oldicons1) {
        case '1': this.oneDay(); break;
        case '2': this.oneWeek(); break;
        case '3': this.onMonth(); break;
        case '4': this.oneSeason(); break;
        // case '5': this.oneYear(); break;
      }
    }
  }
  //格式化数据
  getArrData(res) {
    let arr = [];
    for (var key in res) {
      if (!res.hasOwnProperty(key)) {
        continue;
      }
      var item = {};
      item[key] = res[key];
      arr.push(item);
    }
    return arr;
  }
  //日
  oneDay() {
    const now = new Date();
    const nowStamp = now.getTime();
    const aDay = 3600 * 24 * 1000;
    const startday = nowStamp - aDay;
    const startTime = new Date(startday).toLocaleString();
    const endTime = now.toLocaleString();
    const sind = startTime.indexOf('午'), eind = endTime.indexOf("午");

    const start = moment(startTime.slice(0, sind - 1) + startTime.slice(sind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
    const end = moment(endTime.slice(0, eind - 1) + endTime.slice(eind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
    this.starte = 60;
    this.countData(start, end);
    // this.service
    //   .getDayStatistics(this.data.typeTag, this.data.id, this.dataQuota, start, end)
    //   .subscribe(res => {
    //     const data = this.getArrData(res);
    //     this.avg = res[data.length - 1].avg.toFixed(3)
    //     this.max = res[data.length - 1].max.toFixed(3)
    //     this.min = res[data.length - 1].min.toFixed(3)
    //   })
  }

  //周
  oneWeek() {
    const now = new Date();
    const nowStamp = now.getTime();
    const aDay = 3600 * 24 * 1000 * 7;;
    const startday = nowStamp - aDay;
    const startTime = new Date(startday).toLocaleString();
    const endTime = now.toLocaleString();
    const sind = startTime.indexOf('午'), eind = endTime.indexOf("午");

    const start = moment(startTime.slice(0, sind - 1) + startTime.slice(sind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
    const end = moment(endTime.slice(0, eind - 1) + endTime.slice(eind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
    this.starte = 95;
    // this.gettimehistory(start, end);
    this.countData(start, end);
    //getWeekStatistics
    // this.service
    //   .getWeekStatistics(this.data.typeTag, this.data.id, this.dataQuota, start, end)
    //   .subscribe(res => {
    //     const data = this.getArrData(res);
    //     this.avg = res[data.length - 1].avg.toFixed(3)
    //     this.max = res[data.length - 1].max.toFixed(3)
    //     this.min = res[data.length - 1].min.toFixed(3)
    //   })
  }

  //月
  onMonth() {
    const now = new Date();
    // 获取当前月份
    const currMonth = now.getMonth();
    // 当前月份减一
    const startMonth = currMonth - 1;
    const startTime = new Date(new Date().setMonth(startMonth)).toLocaleString();
    const endTime = now.toLocaleString();
    const sind = startTime.indexOf('午'), eind = endTime.indexOf("午");

    const start = moment(startTime.slice(0, sind - 1) + startTime.slice(sind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
    const end = moment(endTime.slice(0, eind - 1) + endTime.slice(eind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
    this.starte = 95;
    // this.gettimehistory(start, end);
    this.countData(start, end);

    // this.service
    //   .getMonthStatistics(this.data.typeTag, this.data.id, this.dataQuota, start, end)
    //   .subscribe(res => {
    //     const data = this.getArrData(res);
    //     this.avg = res[data.length - 1].avg.toFixed(3)
    //     this.max = res[data.length - 1].max.toFixed(3)
    //     this.min = res[data.length - 1].min.toFixed(3)
    //   })

  }

  //季
  oneSeason() {
    const now = new Date();
    const currMonth = now.getMonth();
    const startMonth = currMonth - 3;
    const startTime = new Date(new Date().setMonth(startMonth)).toLocaleString();
    const endTime = now.toLocaleString();
    const sind = startTime.indexOf('午'), eind = endTime.indexOf("午");

    const start = moment(startTime.slice(0, sind - 1) + startTime.slice(sind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
    const end = moment(endTime.slice(0, eind - 1) + endTime.slice(eind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
    this.starte = 95;
    // this.gettimehistory(start, end);
    this.countData(start, end);

    // this.service
    //   .getSeasonStatistics(this.data.typeTag, this.data.id, this.dataQuota, start, end)
    //   .subscribe(res => {
    //     const data = this.getArrData(res);
    //     this.avg = res[data.length - 1].avg.toFixed(3)
    //     this.max = res[data.length - 1].max.toFixed(3)
    //     this.min = res[data.length - 1].min.toFixed(3)
    //   })
  }

  //年
  /*   oneYear() {
      const now = new Date();
      const curYear = now.getFullYear();
      const startYear = curYear - 1;
      const startTime = new Date(new Date().setFullYear(startYear)).toLocaleString();
      const endTime = now.toLocaleString();
      const sind = startTime.indexOf('午'), eind = endTime.indexOf("午");
  
      const start = moment(startTime.slice(0, sind - 1) + startTime.slice(sind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
      const end = moment(endTime.slice(0, eind - 1) + endTime.slice(eind + 1), "YYYY/M/D HH:mm:ss").format("YYYYMMDDHHmmssSSS");
      this.starte = 95;
      this.gettimehistory(start, end);
    } */

  go(e) {
    const target = e.target;    //获取点击项
    let value = $(target).attr('value');
    if (value == "camera") {
      $('.start').hide();
      $('.end').hide();
      $('.time').hide();
      $('#chart').show();
      $('#chart1').hide();
      $(".search").hide();
      this.va = false;

    } else {
      $('.start').show()
      $('.end').show();
      $('.time').show();
      $('#chart').hide();
      $('#chart1').show();
      $(".search").show();
      $(".values").show();
      this.va = true;

      this.oneDay();

      $('#chart1').children('div').eq(0).css('height', '100%');
      $('#chart1').children('div').eq(0).children("canvas").css('height', '100%');
      const ec1 = echarts as any;
      const container1 = document.getElementById('chart1');
      this.echart1 = ec1.init(container1);
      if (this.chart1 != undefined) {
        this.echart1.setOption(this.chart1);
      } else {
        $(".time").hide()
      }
    }
  }
  goList() {
    this.navCtrl.push(ListPage, {
      type: this.data.typeTag,
      id: this.data.id,
      title: this.data.code,
      typeNumber :this.data.type
    });
  }

  //实时数据
  real() {
    if (this.subscribed) {
      return
    }
    //状态
    this.state$ = this.directives.state
      .map((state: number) => {
        StompState[state]
      })
    let url = "/topic/data/" + this.data.typeTag + "/" + this.data.id
    // 订阅的主题
    this.message$ = this.directives
      .subscribe(url);
    this.subscription$ =
      this.message$
        .map((message: Message) => JSON.parse(message.body, (k, v) => {
          if (k === 'time') {
            return moment(v, 'YYYYMMDDHHmmss').toDate();
          }
          return v;
        }))
        .subscribe((data: any) => {
          const sum = this.count * this.avg + data.data[0];
          const avg = sum / (this.count + 1);
          this.avg = avg.toFixed(3);
          if (data.data[0] > parseFloat(this.max)) {
            this.max = data.data[0].toFixed(3)
          }
          if (data.data[0] < parseFloat(this.min)) {
            this.min = data.data[0].toFixed(3)
          }
          this.chartX.shift();
          this.chartX.push(this.getTime(data.time))
          this.chartY.map((item, i) => {
            item.shift()
            item.push(data.data[i].toFixed(3))
          })
          this.starte = 50;
          this.chart = this.getecharts(this.chartX, this.chartY, '10%');
          this.echart.setOption(this.chart)
        });

    this.subscribed = true
  }
  getTime(t) {
    const time = new Date(t)
    const year = time.getFullYear()  < 10 ? "0" + (time.getFullYear()) : (time.getFullYear());
    const month = 
        time.getMonth() + 1 < 10 ? "0" + (time.getMonth() + 1) : (time.getMonth() + 1),
      day = time.getDate() < 10 ? "0" + time.getDate() : time.getDate(),
      hours = time.getHours() < 10 ? "0" + time.getHours() : time.getHours(),
      minutes = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes(),
      s = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds();
    const data = year+"/"+month + "/" + day + "/" + hours + ":" + minutes+":"+s;
    return data
  }
  unsubscribe() {
    if (!this.subscribed) {
      return
    }
    this.subscription$.unsubscribe()
    this.subscription$ = null
    this.message$ = null
    this.subscribed = false
  }
}
